package com.example.service;


import com.example.index.Customer;
import com.example.repository.CustomerRepository;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;

@Repository
public class CustomerService {

    @Resource
    CustomerRepository repository;

    @Resource
    ElasticsearchRestTemplate elasticsearchRestTemplate;

    public void fetchPageCustomers() {
        Sort sort = Sort.by(Sort.Direction.DESC, "address.keyword");
        Pageable pageable = PageRequest.of(0, 10, sort);

        Page<Customer> customers = repository.findByAddress("广州", pageable);

        List<Customer> content = customers.getContent();

        long totalElements = customers.getTotalElements();
        int totalPages = customers.getTotalPages();

    }


    public void testElasticsearchRestTemplate() {

        // 新建一个QueryBuilder（该对象是Elasticsearch的，QueryBuilders可以构建各种各样的条件查询）
        QueryBuilder queryBuilder = QueryBuilders.matchQuery("address" , "广州");
        // 新建一个Query（该对象是Spring Data Elasticsearch的）
        Query query = new NativeSearchQueryBuilder().withQuery(queryBuilder).build();
        // 使用template执行查询，SearchHits<User>就是执行后的返回结果的映射实体

        SearchHits<Customer> search = elasticsearchRestTemplate.search(query, Customer.class);
    }


}
